<?php
/**
 * 入住信息同步
 * User: allen_ios
 * Date: 16/11/24
 * Time: 上午11:53
 */

namespace Task\App\Doorbjhq;
use Task\Core\Base;
use Task\Core\Http;

class SyncDoorbjhqUser extends Base
{
    protected $mysql;

    public function __construct()
    {
        parent::__construct();
        $this->mysql = $this->selectDB('mysql');
        $ntime = date("Y-m-d H:i:s",time());
//        error_log("account_id:{$ntime}--11212121\r\n",3,"/mnt/tasklog/pullTaskData.log");
    }


    public function getUserList($account_id)
    {
        set_time_limit(0);

        $time = strtotime(date('Y-m-d'));
        $sql = "select user_id,user_name,number,room_sex,building_id from gc_apartment_info
                where account_id = ".$account_id." and type != 3 and (create_time > $time or update_time > $time)";

        $result = $this->mysql->query($sql)->fetchAll(\PDO::FETCH_ASSOC);

        $functionName = 'AddUpdateUserEx';
        foreach($result as $k=>$v) {
            $params = array(
                'user' => array(
                    'userName' => $v['user_name'],
                    'sex' => $v['room_sex'],
                    'userNum' => $v['number'],
                    'outID' => $v['user_id'],
                    'outDepartID' => $v['building_id']
                )
            );
            //同步入住的信息到平治
            $aa = DoorctrlBjhqApi::callApi($functionName, $params);
            wLog('doorbjhq:'.var_export($aa,true).'/n', 'doorbjhq-getUserList');

            //同时开卡
            //先去统计平台查询，此学号对应的一卡通卡号，进行开卡操作

            $res = Http::curlPostApartment(config('STAT_CARD_URL'),array('userNum'=>$v['number']));

            if($res['Success'] == false){
                $openResMsg = '没有此工号'.$v["number"].'对应的一卡通卡号的信息,开卡失败';
                wLog('isexistcard:'.$openResMsg.'/n', 'doorbjhq-getUserList');
                continue;
            }else{
                //通过post请求回来的一卡通卡号存在,但是姓名不匹配
                $resArr = json_decode($res['data'],true);
                $cardNum = trim($resArr['CardNO'],' ');
                //匹配中文字符和去空格（一卡通查来的名字）
                preg_match("/[\x{4e00}-\x{9fa5}]+/u",$resArr['AccName'], $resArr['AccName']);
                $userName = preg_replace('# #','',$resArr['AccName'][0]);
                $nameArr = array();
                //匹配中文字符（循环出来的名字）
                preg_match("/[\x{4e00}-\x{9fa5}]+/u",$v['user_name'], $nameArr);
                $name = preg_replace('# #','',$nameArr[0]);

                if($cardNum && $userName != $name){
//                    $this->ajaxReturn(array('status'=>'F','message'=>'此工号和一卡通卡号对应的姓名不匹配，请核实!'));
                    $openResMsg = '姓名不匹配:'.$userName.'--'.$name.'此工号和一卡通卡号对应的姓名不匹配,开卡失败';
                    wLog('notMatchName:'.$openResMsg.'/n', 'doorbjhq-getUserList');
                    continue;
                }

                //通过post请求回来的一卡通卡号，开卡
                $datas = array(
                    'card_num' => $cardNum,
                    'user_id' => $v['user_id'],
                    'user_name' => $v['user_name'],
                    'number' => $v['number']
                );

                //开卡操作
                $openRes = $this->openCard($datas);
            }
        }

    }

    /**
     * 开卡操作
     * @param array $data 开卡数据
     */
    public function openCard($data)
    {
        if (!$data['user_id'] || !isset($data['card_num']) ) {
            return;
        }

        //卡入库,如果存在就更新
        $sql = "select count(*) as count from gc_door_card where user_id = ".$data['user_id']." and card_num = ".$data['card_num']." and status = 1 and cut_off = 0";

        $isExist = $this->mysql->query($sql)->fetch(\PDO::FETCH_ASSOC);

        if ($isExist['count'] == 0) {
            //已存在此用户的未注销的别的卡，（挂失了卡，重新开了卡，未在平治这边开卡，未开通门禁的情况，将此用户的卡的信息更新）
            $sqls = "select count(*) as count from gc_door_card where user_id = ".$data['user_id']." and status = 1 and cut_off = 0";

            $userCard = $this->mysql->query($sqls)->fetch(\PDO::FETCH_ASSOC);

            if($userCard['count'] != 0){
                //更新此用户的卡信息
                $openCardSql = "update gc_door_card set card_num = '".$data['card_num']."',update_time = ".time()." where user_id = ".$data['user_id']." and status = 1 and cut_off = 0";
            }else{
                //开卡
                $openCardSql = "insert into gc_door_card(apply_id,card_num,user_id,user_name,user_num,status,cut_off,create_time) values(1,'".$data['card_num']."',".$data['user_id'].",'".$data['user_name']."','".$data['number']."',1,0,".time().")";
            }
            /*if($data['number'] == '150726'){
                $testSql = "insert into gc_test_log(content,num) values('".$openCardSql."',3)";
                $this->mysql->query($testSql);
            }*/
            $this->mysql->query($openCardSql);
        }

        //调用开卡接口
        $params = array(
            'userCardCode' => array(
                'outUserId' => $data['user_id'],
                'cardCode' => $data['card_num']
            )   
        );
        $functionName = 'openCard';

        $res = DoorctrlBjhqApi::callApi($functionName, $params);
        wLog('doorbjhq_opencard:'.var_export($res,true).'---学号:'.$data['number'].'--姓名:'.$data['user_name'].'/n', 'doorbjhq-getUserList');
    }

    /**
     * 开卡操作
     * @param array $data 开卡数据
     */
    public function Test()
    {
        //调用开卡接口
        /*$params = array(
            'userCardCode' => array(
                'outUserId' => '62538',
                'cardCode' => '3059954831'
            )
        );
        $functionName = 'openCard';

        $res = DoorctrlBjhqApi::callApi($functionName, $params);
        cdump(var_export($res,true)['Message']);*/

        $res = Http::curlPostApartment('http://183.129.235.99:9001/DoorctrlBjhq/EventApi/checkCardInfo',array('userNum'=>'201714302520009'));
        cdump(json_decode($res,true));
        cdump(json_decode($res['data'],true));
    }
}